package net.searchdata.ref;

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.junit.Test;

public class Entry28Two {
	public <E> Set<E> union(Set<? extends E> set1, Set<? extends E> set2) {
		Set<E> set = new HashSet<E>(set1);
		set.addAll(set2);

		return set;
	}

	public <T extends Comparable<? super T>> T max(List<? extends T> list) {
		Iterator<? extends T> it = list.iterator();
		T result = it.next();

		while (it.hasNext()) {
			T t = it.next();
			result = (result.compareTo(t) > 0) ? result : t;
		}

		return result;
	}

	public <T extends Comparable<T>> T max2(List<T> list) {
		Iterator<T> it = list.iterator();
		T result = it.next();

		while (it.hasNext()) {
			T t = it.next();
			result = (result.compareTo(t) > 0) ? result : t;
		}

		return result;
	}

	public void swap(List<?> list, int i, int j) {
		swapHelper(list, i, j);
	}

	private <E> void swapHelper(List<E> list, int i, int j) {
		list.set(i, list.set(j, list.get(i)));
	}

	@Test
	public void testUnion() {
		Set<Integer> intSet1 = new HashSet<Integer>();
		Set<Double> intSet2 = new HashSet<Double>();

		intSet1.addAll(Arrays.asList(1, 2, 3));
		intSet2.addAll(Arrays.asList(5.0, 6.0, 7.0));

		Set<Number> set = this.<Number> union(intSet1, intSet2);
		assertThat(set.size(), is(6));
	}

	@Test
	public void testMax() {
		int max = max(Arrays.asList(3, 2, 5, 9, 10, 1000));
		assertThat(max, is(1000));
	}

	@Test
	public void testSwap() {
		List<Integer> list = Arrays.asList(1, 2, 3);

		swap(list, 0, 2);

		assertThat(list.get(0), is(3));
		assertThat(list.get(2), is(1));
	}
}